//创建用户信息相关的仓库
import { defineStore } from 'pinia'
//引入登录接口
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/user/index.ts'
//引入state ts类型
import userState from './type.ts'
//引入数据类型
import type { loginForm, loginToken, dataObj } from '@/api/user/type.ts'
import { SET_TOKEN, GET_TOKEN, DEL_TOKEN } from '@/utils/token.ts'
//引入路由
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes.ts'
import router from '@/router/index.ts'
import cloneDeep from 'loadsh/cloneDeep'

function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
//引入本地存储的工具方法
const userStore = defineStore('User', {
  //存储数据
  state: (): userState => {
    return {
      token: GET_TOKEN() || '', //唯一标识
      menuRoute: constantRoute, //路由生成左侧菜单
      userInfo: {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: '',
      },
    }
  },
  //异步处理
  actions: {
    //用户登录
    async userLogin(data: loginForm) {
      const userData: loginToken = await reqLogin(data)

      //200成功
      //201失败
      if (userData.code === 200) {
        // token唯一标识
        this.token = userData.data as string
        SET_TOKEN(userData.data as string)
      } else {
        // 失败通过promise来返回
        return Promise.reject(new Error(userData.data))
      }
    },
    //退出操作
    async userOutLogin() {
      //清除pinia中的token和本地存储的token
      const res = await reqLogOut()
      if (res.code == 200) {
        this.token = ''
        DEL_TOKEN()
        this.userInfo = {
          routes: [],
          buttons: [],
          roles: [],
          name: '',
          avatar: '',
        }
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async setUserInfo() {
      const userData: dataObj = await reqUserInfo()
      if (userData.code == 200) {
        this.userInfo = userData.data
        const userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRoute),
          userData.data.routes,
        )
        this.menuRoute = [...constantRoute, ...userAsyncRoute, anyRoute]
          ;[...userAsyncRoute, anyRoute].forEach((item) => {
            router.addRoute(item)
          })
        return 'ok'
      } else {
        return Promise.reject(new Error(userData.message))
      }
    },
  },
  getters: {},
})
export default userStore
